#!/usr/bin/perl

# ---------- Init variables -------
#my $version = "0.0001";
# ---------- external readable parameters -------
## Functions
##-------------------------------------------------------
#
# stict syntax checking.
use strict;
use CGI qw(param);
use SIM_settings;
use SIM_base;

#BEGIN { $Exporter::Verbose=1 }

# Startupscript translater
my $module = $ARGV[0];
my $tool = $ARGV[1];
my $action = $ARGV[2];
my $option1 = $ARGV[3];
my $option2 = $ARGV[4];
my $option3 = $ARGV[5];



my $backHeader="black";
my $httpUser = $ENV{'REMOTE_USER'};
my $httpReF = $ENV{'HTTP_REFERER'};
my $httpScriptName = $ENV{'SCRIPT_NAME'};
my $httpUserIp = $ENV{'REMOTE_ADDR'};
my $httpServerName = $ENV{'HTTP_HOST'};
my $httpCookie = $ENV{'HTTP_COOKIE'};
my $httpHost = $ENV{'HTTP_HOST'};
my $pluginDir = $ENV{'SIM_PLUGINSDIR'};
my $simStarter = $ENV{'SIM_STARTER'};
my $simDomain = $ENV{'SIM_MANDOMAIN'};
my $starterMenuFile = $ENV{'SIM_STARTERITEMS'} || die "cannot read SIM_STARTERITEMS."; 

sub printMenu {
  my $configFile = $SIMparam{'SIMcronJobs'};
  my %cronEntries = ();
  open( IN, $configFile);
  my @lines = <IN>;
  close IN;
  foreach my $regel (@lines) {
    chomp $regel;
    my ( $type, $time, $action, $domains, $day ) = split(' ', $regel);
    if (( $type eq "c" ) or ( $type eq "s" )) {
      $cronEntries{$action} = "$type $time $domains $day";
    }
  }
  print("<CENTER><TABLE>
     <TR BGCOLOR=#DDDDDD>
       <TD>Last run</TD>
       <TD>CronEntry</TD>
       <TD>Action</TD>
       <TD>Description</TD>
     </TR>");
  open (MENUFILE, "$starterMenuFile");
  while (my $regel = <MENUFILE>) {
    my ( $command, $type, $description ) = split(' ', $regel, 3);
    if ( "$command" eq "MENU" ) {
      print("<TR><TD></TD><TD></TD><TD></TD><TD><B>$type $description</B></TD></TR>");
    } else {
      my $logDir = "$SIMparam{'SIMlogDir'}/$type-$command";
      my $time = (stat($logDir))[9];
      my ($dateString , $timeString);
      if ( $time ne "" ) {
        $dateString = printDate($time,"yyyymmdd");
        $timeString = printDate($time,"hhmmss");
      }
      print("<TR BGCOLOR=#EEEEEE VALIGN=top><TD>$dateString $timeString</TD><TD>$cronEntries{$command}</TD><TD><A HREF=$httpScriptName?$module+$tool+$type+$command>$command</A></TD><TD>$description</TD></TR>");    
    }
  }
  print("</TABLE>");
}

sub startStarter {
  my $type = "@_[0]";
  my $action = "@_[1]";
  if (( -x "$simStarter" ) and ( "$type" eq "sh" )) {
    print("</CENTER><PRE>");
    system("$simStarter $action $simDomain verbose");
    print("</PRE>");
  } elsif (( -x $SIMparam{'SIMperlStarter'} ) and ( "$type" eq "pl" )) {
    print("</CENTER><PRE>");
    system(" $SIMparam{'SIMperlStarter'} $action $simDomain verbose");
    print("</PRE>");
  } else {
    print("oops, no Sipman starter found (type=$type, action=$action).");
  }
}

#--------------------------- Main ---------------------------
if ( "$action" eq "none" ) {
  printMenu;
} else {
  startStarter($action, $option1);
}
